package com.topisv.tms.web.auth;

import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.taobao.api.internal.util.WebUtils;
import com.topisv.tms.entity.ShopSource;
import com.topisv.tms.entity.auth.TopisvOAuth;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.ShopSourceService;
import com.topisv.tms.utils.InitProperties;
import com.topisv.tms.web.base.BaseController;

/**
 * 商家授权
 * @author ch
 *
 */
@Controller
@RequestMapping(value = "/v2_auth")
public class AuthController extends BaseController {
	
	 //沙箱环境
//    private final String regAppKey="1023011794";
//	private final String regAppSecret="sandbox529570f1caf3d93919295eafe";
//	private final String regCodeUrl="https://oauth.tbsandbox.com/authorize";
//	private final String regTokenUrl="https://oauth.tbsandbox.com/token";
//	private final String regServer="http://gw.api.tbsandbox.com/router/rest";
//	private final String redirect_uri="http://top.paiu.com.cn/wms/v2_auth/code";
	
	
	//正式环境
    private final String regAppKey=InitProperties.get("regAppKey");
	private final String regAppSecret=InitProperties.get("regAppSecret");
	private final String regCodeUrl="https://oauth.taobao.com/authorize";
	private final String regTokenUrl="https://oauth.taobao.com/token";
	private final String regServer="http://gw.api.taobao.com/router/rest";
	private final String redirect_uri=InitProperties.get("redirect_uri");
	
	@Autowired
	private ShopSourceService shopSourceService;
	@Autowired
	private CustomersService customerService;
	
	
	@RequestMapping(method = RequestMethod.GET)
	public String auth() {
		return "auth/auth";
	}
	
	
	/**
	 * 商家授权回调方法
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "code")
	public String code(HttpServletRequest request, HttpServletResponse response) {
		
		JSONObject json=null;
		PrintWriter out=null;
		String resultResponse="";
	    try {
	    	response.setCharacterEncoding("utf-8");
	    	json=new JSONObject();
	    	out=response.getWriter();
	    	log.info("淘宝商家开始授权");
	    	log.info("redirect_uri:"+redirect_uri);
	    	
//	    	Enumeration<String> keys=request.getParameterNames();
//	    	while(keys.hasMoreElements()){
//	    		String key=keys.nextElement();
//	    	}
	    	
	    	 String code=request.getParameter("code");
	    	 if(null == code) //获取授权码失败
	    	 {
	    		 log.info("授权失败----------");
	    		 out.print("<B>please authorize again .</B>");
	    		 String error=request.getParameter("error");
	    		 if(null == error)
	    		 {
	    			 return "redirect:"+regCodeUrl+"?state=paiu&client_id="+regAppKey+"&response_type=code&redirect_uri="+redirect_uri;
	    		 }
	    		 else
	    		 {
	    			 return null;
	    		 }
	    	 }
	    	 else //获取授权码成功
	    	 {
	    		 ShopSource shopSource=this.shopSourceService.findByTopisvCode(code);
	    		 log.info("code:"+code);
	    		 if(shopSource != null)
	    		 {
	    			 return "redirect:/tblogin/"+shopSource.getTopisvNick()+"/" + shopSource.getR1ExpiresIn();
	    		 }
	    	 }
	    	 
	    	 log.info("授权码："+code);
	    	 
	    	 //封装参数，获取令牌
	    	 Map<String, String> param = new HashMap<String, String>();
	    	 param.put("grant_type", "authorization_code");
	    	 param.put("code", code);
	    	 param.put("client_id", regAppKey);
	    	 param.put("client_secret", regAppSecret);
	    	 param.put("redirect_uri", redirect_uri);
	    	 param.put("view", "web");
	    	 param.put("state", "state");
	    	 String result=WebUtils.doPost(regTokenUrl, param, 3000, 3000);
	    	 
	    	 json=JSONObject.fromObject(result);
	    	 String access_token=json.getString("access_token");
	    	 String token_type=json.getString("token_type");
	    	 String expires_in=json.getString("expires_in");
	    	 String r1_expires_in=json.getString("r1_expires_in");
	    	 String r2_expires_in=json.getString("r2_expires_in");
	    	 String w1_expires_in=json.getString("w1_expires_in");
	    	 String w2_expires_in=json.getString("w2_expires_in");
	    	 String taobao_user_nick=json.getString("taobao_user_nick");
	    	 String taobao_user_id=json.getString("taobao_user_id");
	    	 String refresh_token=json.getString("refresh_token");
	    	 taobao_user_nick=URLDecoder.decode(taobao_user_nick,"UTF-8");
	    	 

			 TopisvOAuth topisvOAuth=new TopisvOAuth();
		     topisvOAuth.setAppKey(regAppKey);
		     topisvOAuth.setAppSecret(regAppSecret);
		     topisvOAuth.setServerUrl(regServer);
		     topisvOAuth.setSessionKey(access_token);
		     topisvOAuth.setTopisvRds("jrdswcmq2pge");
		     
	    	 ShopSource shopSource=this.shopSourceService.findByTopisvNick(taobao_user_nick);
	    	 if(shopSource==null){
	    		log.info("找不到店铺");
	    		resultResponse+="该用户不存在";
	    		
	    		shopSource=new ShopSource();
				shopSource.setCreateDate(new Date());
				shopSource.setOrdenoSourceCode("tNormal");
				shopSource.setShopName(taobao_user_nick);
				shopSource.setStatus("normal");
				shopSource.setCustomerType("SOPL");
				shopSource.setTopisvRds("jrdswcmq2pge");
				shopSource.setBillNo("yes");
				shopSource.setOrderType("-1");
				shopSource.setPayAfter("no");
				shopSource.setWareType("yes");
				shopSource.setLogType("yes");
				shopSource.setTopisvUserId(taobao_user_id);
		    	shopSource.setTopisvSessionKey(access_token);	
		    	shopSource.setExpiresIn(expires_in);
		    	shopSource.setRefreshToken(refresh_token);
		    	shopSource.setTopisvKey(regAppKey);
		    	shopSource.setTopisvSecret(regAppSecret);
		    	shopSource.setTopisvServerUrl(regServer);
		    	shopSource.setTopisvNick(taobao_user_nick);
		    	shopSource.setTopisvCode(code);
	    		customerService.registerTaobao(shopSource,topisvOAuth);
	    		
	    	}else{
	    		shopSource.setTopisvUserId(taobao_user_id);
		    	shopSource.setTopisvSessionKey(access_token);	
		    	shopSource.setExpiresIn(expires_in);
		    	shopSource.setRefreshToken(refresh_token);
		    	this.shopSourceService.save(shopSource);
	    	}
	    	
	    	//创建用户名和密码的令牌
			UsernamePasswordToken token = new UsernamePasswordToken(shopSource.getTopisvNick(),shopSource.getR1ExpiresIn());
			//记录该令牌，如果不记录则类似购物车功能不能使用。
			token.setRememberMe(true);
			//subject理解成权限对象。类似user
			Subject subject = SecurityUtils.getSubject();
			try {
			     subject.login(token);
			} catch (UnknownAccountException ex) {//用户名没有找到。
				return "taobao/tbLook";
			} catch (IncorrectCredentialsException ex) {//用户名密码不匹配。
				return null;
			 }catch (AuthenticationException e) {//其他的登录错误
				 return null;
			}
			//验证是否成功登录的方法
			if (subject.isAuthenticated()) {
				log.info("{} login.",shopSource.getTopisvNick());
			}
			return "redirect:/";
	    	
	    	
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(resultResponse+"==="+json.toString());
			log.error("error",e);
			
		}
		return "redirect:/v2/login";
	}

}
